package com.suyl.annotationdemo.model.controller;

import com.suyl.annotationdemo.core.annotation.Person;
import com.suyl.annotationdemo.model.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;

/**
 * @author : suyl
 * @version : v1.0.0
 * @date : 2020/3/20 15:02
 * @descr : Description
 */
@RestController
public class TestAnnotationController {

    @GetMapping("anno")
    public String anno(String name) throws IllegalAccessException, InstantiationException {
        return validator(User.builder().name(name).build());
    }

    @GetMapping("test")
    public String test() {
        return "test success...";
    }

    public String validator(User user) throws IllegalAccessException, InstantiationException {
        String result = null;
        Field[] fields = user.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            System.out.println(field.getName());
            System.out.println(field.get(user));
            Person excelField = field.getAnnotation(Person.class);
            if (null != excelField) {
                Class<?> emptyClazz = Person.Void.class;
                try {
                    if (excelField.validator() != emptyClazz) {
                        result = excelField.validator().newInstance().valid(field.get(user));
                    }
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
